/*
 * EnigmaGM - A feature rich guild management system.
 * Copyright (C) 2007 ajiaojr.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
package org.ajiaojr.enigmagm.server;

import org.ajiaojr.enigmagm.client.UserException;
import org.ajiaojr.enigmagm.client.data.User;
import org.ajiaojr.enigmagm.client.service.DataAccessException;
import org.ajiaojr.enigmagm.client.service.UserService;
import org.ajiaojr.enigmagm.db.DAOManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserServiceImpl extends RemoteServiceServlet implements
    UserService {
  private static final Log LOG = LogFactory.getLog(UserServiceImpl.class);

  /**
   * 
   */
  private static final long serialVersionUID = -5737369752021775942L;

  /*
   * (non-Javadoc)
   * 
   * @see org.ajiaojr.enigmagm.client.service.UserService#list(int, int)
   */
  public List list(int firstResult, int maxResults) throws UserException,
      DataAccessException {
    List result = new ArrayList();

    return result;
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.ajiaojr.enigmagm.client.service.UserService#login(java.lang.String,
   *      java.lang.String, boolean)
   */
  public User login(String username, String password, boolean saveLogin)
      throws UserException, DataAccessException {
    User u = DAOManager.getInstance().getUserDAO().login(username, password);

    if (u == null) {
      if (LOG.isWarnEnabled()) {
        LOG.warn("Failed login. Username: " + username + ", IP address: "
            + getThreadLocalRequest().getHeader("X-Forwarded-for"));
      }
      throw new UserException("Incorrect login information provided");
    }

    // Invalidate the current session.
    HttpSession session = this.getThreadLocalRequest().getSession(false);
    if (session != null) {
      session.invalidate();
    }

    // Create a fresh session and sets the User attribute.
    session = this.getThreadLocalRequest().getSession(true);
    session.setAttribute("User", u);

    HttpServletResponse response = getThreadLocalResponse();

    Cookie usernameCookie = new Cookie("USERNAME", username);
    usernameCookie.setPath("/");
    usernameCookie.setMaxAge(60 * 60 * 24 * 365);
    response.addCookie(usernameCookie);

    String authToken = RandomStringUtils.random(32, true, true);

    DAOManager.getInstance().getUserDAO().saveAuthToken(username, authToken);

    Cookie authTokenCookie = new Cookie("AUTH_TOKEN", authToken);
    authTokenCookie.setPath("/");
    authTokenCookie.setMaxAge(saveLogin ? 60 * 60 * 24 * 365 : -1);
    response.addCookie(authTokenCookie);

    if (LOG.isInfoEnabled()) {
      LOG.info("User " + username + " logged in successfully");
    }

    return u;
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.ajiaojr.enigmagm.client.service.UserService#loginViaCookie()
   */
  public User loginViaAuthToken() throws UserException, DataAccessException {
    String username = null;
    String authToken = null;

    Cookie[] cookies = getThreadLocalRequest().getCookies();
    for (int i = 0; (i < cookies.length)
        && (username == null || authToken == null); i++) {
      Cookie cookie = cookies[i];
      if (cookie.getName().equals("USERNAME")) {
        username = cookie.getValue();
      } else if (cookie.getName().equals("AUTH_TOKEN")) {
        authToken = cookie.getValue();
      }
    }

    User u =
        DAOManager.getInstance().getUserDAO().loginViaAuthToken(username,
            authToken);

    if (u == null) {
      if (LOG.isWarnEnabled()) {
        LOG.warn("Failed login. Username: " + username + ", IP address: "
            + getThreadLocalRequest().getHeader("X-Forwarded-for"));
      }
      throw new UserException("Incorrect login information provided");
    }
    // Invalidate the current session.
    HttpSession session = this.getThreadLocalRequest().getSession(false);
    if (session != null) {
      session.invalidate();
    }

    // Create a fresh session and sets the User attribute.
    session = this.getThreadLocalRequest().getSession(true);
    session.setAttribute("User", u);

    if (LOG.isInfoEnabled()) {
      LOG.info("User " + username + " logged in successfully");
    }

    return u;
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.ajiaojr.enigmagm.client.service.UserService#logout()
   */
  public void logout() {
    HttpSession session = this.getThreadLocalRequest().getSession(false);
    if (session != null) {
      session.invalidate();
    }

    HttpServletResponse response = getThreadLocalResponse();
    Cookie authTokenCookie = new Cookie("AUTH_TOKEN", null);
    authTokenCookie.setMaxAge(0);
    authTokenCookie.setPath("/");
    response.addCookie(authTokenCookie);
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.ajiaojr.enigmagm.client.service.UserService#register(java.lang.String,
   *      java.lang.String)
   */
  public void register(String username, String password) throws UserException,
      DataAccessException {
    DAOManager.getInstance().getUserDAO().register(username, password);
  }
}
